package cn.gs.dmw.service.impl;

import cn.gs.dmw.mapper.UserInfoMapper;
import cn.gs.dmw.pojo.UserInfo;
import cn.gs.dmw.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.stereotype.Service;

@Service
public class UserInfoServiceImpl implements UserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public UserInfo findUserById(Integer userId) {
        String redisKey = "userId:" + userId;
        if (redisTemplate.hasKey(redisKey)) {
            System.out.println("执行缓存：");
            redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<UserInfo>(UserInfo.class));
            UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(redisKey);
            return userInfo;
        }
        System.out.println("查询数据库：");
        UserInfo userInfo = userInfoMapper.findUserById(userId);
        redisTemplate.opsForValue().set(redisKey, userInfo);
        return userInfo;
    }

}
